import 'dart:convert';
import 'dart:ui';

import 'package:common_utils/common_utils.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/res/constant.dart';
import 'package:flutter_deer/util/theme_utils.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:intl/intl.dart';
import 'package:keyboard_actions/keyboard_actions_config.dart';
import 'package:keyboard_actions/keyboard_actions_item.dart';
import 'package:sp_util/sp_util.dart';
import 'package:url_launcher/url_launcher.dart';

class Utils {
  /// 打开链接
  static Future<void> launchWebURL(String url) async {
    final Uri uri = Uri.parse(url);
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      Toast.show('打开链接失败！');
    }
  }

  /// 调起拨号页
  static Future<void> launchTelURL(String phone) async {
    final Uri uri = Uri.parse('tel:$phone');
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      Toast.show('拨号失败！');
    }
  }

  static String formatPrice(String price, {MoneyFormat format = MoneyFormat.END_INTEGER}) {
    return MoneyUtil.changeYWithUnit(NumUtil.getDoubleByValueStr(price) ?? 0, MoneyUnit.YUAN, format: format);
  }

  static KeyboardActionsConfig getKeyboardActionsConfig(BuildContext context, List<FocusNode> list) {
    return KeyboardActionsConfig(
      keyboardBarColor: ThemeUtils.getKeyboardActionsColor(context),
      actions: List.generate(
          list.length,
          (i) => KeyboardActionsItem(
                focusNode: list[i],
                toolbarButtons: [
                  (node) {
                    return GestureDetector(
                      onTap: () => node.unfocus(),
                      child: Padding(
                        padding: const EdgeInsets.only(right: 16.0),
                        child: Text(getCurrLocale() == 'zh' ? '关闭' : 'Close'),
                      ),
                    );
                  },
                ],
              )),
    );
  }

  ///
  static String? getCurrLocale() {
    final String locale = SpUtil.getString(Constant.locale)!;
    if (locale == '') {
      return PlatformDispatcher.instance.locale.languageCode;
    }
    return locale;
  }

  /// 将 2023-12-06T22:50:22 格式的时间字符串转化为时间戳
  static int timeStamp(String? time) {
    // 检查传入的时间字符串是否为 null 或空字符串，如果是则直接返回 0
    if (time == null || time.isEmpty) {
      return 0;
    }
    try {
      // 使用 DateTime.parse 方法解析时间字符串
      final DateTime dateTime = DateTime.parse(time);
      // 获取时间戳（毫秒级）
      final int timestamp = dateTime.millisecondsSinceEpoch;
      if (timestamp <= 0) {
        // 如果时间戳小于等于 0，则返回当前系统时间戳
        return DateTime.now().millisecondsSinceEpoch;
      }
      return timestamp;
    } catch (e) {
      // 捕获解析异常，打印错误信息
      print('Error parsing time: $e');
    }
    // 如果解析失败或出现异常，返回 0
    return 0;
  }

  static final DateFormat dateFormat = DateFormat('yyyy-MM-dd HH:mm:ss');

  /// 获取当前时间 如：2023-12-06 22:50:22
  static String getCurrentTime() {
    final DateTime now = DateTime.now();
    final String formattedTime = dateFormat.format(now);
    return formattedTime;
  }

  /// 获取当前时间戳
  static int getCurrentTimeStamp() {
    return DateTime.now().millisecondsSinceEpoch;
  }
}

/// 显示一个具有弹性动画效果的对话框
///
/// 该函数封装了showGeneralDialog，提供了自定义的过渡动画效果，使对话框具有弹性弹出的效果。
///
/// [context] BuildContext上下文，用于显示对话框
/// [barrierDismissible] 布尔值，控制点击对话框外部是否可以关闭对话框，默认为true
/// [builder] WidgetBuilder，用于构建对话框内容的构造器
///
/// 返回一个Future<T?>，解析为对话框关闭时返回的值，如果对话框被dismissed则返回null
Future<T?> showElasticDialog<T>({
  required BuildContext context,
  bool barrierDismissible = true,
  required WidgetBuilder builder,
}) {
  return showGeneralDialog(
    context: context,
    pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
      final Widget pageChild = Builder(builder: builder);
      return SafeArea(
        child: pageChild,
      );
    },
    barrierDismissible: barrierDismissible,
    barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
    barrierColor: Colors.black54,
    transitionDuration: const Duration(milliseconds: 550),
    transitionBuilder: _buildDialogTransitions,
  );
}


Widget _buildDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
  return FadeTransition(
    opacity: CurvedAnimation(
      parent: animation,
      curve: Curves.easeOut,
    ),
    child: SlideTransition(
      position: Tween<Offset>(begin: const Offset(0.0, 0.3), end: Offset.zero).animate(CurvedAnimation(
        parent: animation,
        curve: const ElasticOutCurve(0.85),
        reverseCurve: Curves.easeOutBack,
      )),
      child: child,
    ),
  );
}

/// String 空安全处理
extension StringExtension on String? {
  String get nullSafe => this ?? '';
}

/// String MD5 加密
extension StringMd5 on String {
  String get toMd5 {
    final content = const Utf8Encoder().convert(this);
    return md5.convert(content).toString();
  }
}
